//
//  ViewController.m
//  ExportCsvDemo
//
//  Created by mac on 2025/9/4.
//

#import "ViewController.h"

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    // Do any additional setup after loading the view.
    
    // 注意：需要关闭沙盒才能直接导出到指定的路径，否则需要授权
    // 授权可以通过打开对话框选择路径实现，但是每次保存都要选择路径，有点麻烦
    // 也可以初次打开对话框选择路径，然后缓存bookmark，下次读取bookmark，就不用每次打开对话框，前提是路径不变，有点复杂
    
    @autoreleasepool {
        NSArray<NSDictionary<NSString *, NSString *> *> *dataArray = @[
            @{@"Name": @"Alice", @"Age": @"25", @"City": @"New York"},
            @{@"Name": @"Bob", @"Age": @"30", @"City": @"Los Angeles"},
            @{@"Name": @"Charlie", @"Age": @"35", @"City": @"Chicago"}
        ];
        NSString *csvString = [self dataArrayToCSVString:dataArray];
        NSString *directoryPath = @"/Users/mac/Desktop/CSVExport";
        NSString *fileName = @"example.csv";
        BOOL success = [self exportCSVString:csvString toDirectory:directoryPath withFileName:fileName];
        if (success) {
            NSLog(@"CSV file exported successfully.");
        } else {
            NSLog(@"Failed to export CSV file.");
        }
    }
}

- (NSString *)dataArrayToCSVString:(NSArray<NSDictionary<NSString *, NSString *> *> *)dataArray {
    NSMutableString *csvString = [NSMutableString string];
    // 写入表头
    NSArray<NSString *> *headers = dataArray.firstObject.allKeys;
    [csvString appendString:[headers componentsJoinedByString:@","]];
    [csvString appendString:@"\n"];
    // 写入数据行
    for (NSDictionary<NSString *, NSString *> *row in dataArray) {
        NSMutableArray<NSString *> *rowValues = [NSMutableArray array];
        for (NSString *header in headers) {
            [rowValues addObject:row[header]];
        }
        [csvString appendString:[rowValues componentsJoinedByString:@","]];
        [csvString appendString:@"\n"];
    }
    return csvString;
}

- (BOOL)exportCSVString:(NSString *)csvString toDirectory:(NSString *)directoryPath withFileName:(NSString *)fileName {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *filePath = [directoryPath stringByAppendingPathComponent:fileName];
    // 创建目录（如果不存在）
    NSError *error;
    if (![fileManager fileExistsAtPath:directoryPath]) {
        [fileManager createDirectoryAtPath:directoryPath withIntermediateDirectories:YES attributes:nil error:&error];
        if (error) {
            NSLog(@"Failed to create directory: %@", error);
            return NO;
        }
    }
    // 写入文件
    return [csvString writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
}

- (void)setRepresentedObject:(id)representedObject {
    [super setRepresentedObject:representedObject];

    // Update the view, if already loaded.
}


@end
